package com.jplus.core.utill;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 流操作工具类
 */
public class StreamUtil {

	private static final Logger logger = LoggerFactory.getLogger(StreamUtil.class);

	public static byte[] toByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[128];
		int n = 0;
		while (-1 != (n = input.read(buffer)))
			output.write(buffer, 0, n);
		input.close();
		return output.toByteArray();
	}

	public static void toWriteFile(File file, byte[] is) {
		FileOutputStream out = null;
		try {
			File fold = file.getParentFile();
			if (!fold.exists())
				fold.mkdirs();
			out = new FileOutputStream(file);
			out.write(is);
			out.flush();
		} catch (Exception e) {
			logger.error("Stream Error:", e);
			throw new RuntimeException(e);
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				logger.error("Stream Close Error:", e);
			}
		}
	}

	public static List<String> toReadFileLine(File file) {
		try {
			byte[] bytes = toReadFile(file);
			List<String> list = Arrays.asList(new String(bytes, "UTF-8").split("\n"));
			return list;
		} catch (UnsupportedEncodingException e) {
			logger.error("Stream Error:", e);
			throw new RuntimeException(e);
		}
	}

	public static byte[] toReadFile(File file) {
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			byte[] filecontent = new byte[(int) file.length()];
			in.read(filecontent);
			return filecontent;
		} catch (Exception e) {
			logger.error("Stream Error:", e);
			throw new RuntimeException(e);
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				logger.error("Stream Close Error:", e);
			}
		}
	}

	public static void toCopy(InputStream inputStream, OutputStream outputStream) {
		try {
			byte[] buffer = toByteArray(inputStream);
			outputStream.write(buffer);
			outputStream.flush();
		} catch (IOException e) {
			logger.error("Stream Error:", e);
			throw new RuntimeException(e);
		} finally {
			try {
				inputStream.close();
				outputStream.close();
			} catch (Exception e) {
				logger.error("Stream Close Error:", e);
			}
		}
	}

}
